<?php

namespace App\Resource\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use App\Common\Middleware\AesMiddleware;
use App\Resource\Request\GoodsRequest;
use App\Resource\Service\GoodsService;
use App\Resource\Service\ResourceService;
use App\Resource\Service\ShareService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;


/**
 *@Controller()
 */
class GoodsController extends AbstractController
{

    /**
     * @Inject()
     * @var GoodsService
     */
    private $goodsService;

    /**
     * @Inject()
     * @var ResourceService
     */
    private $resourceService;

    /**
     * @Inject()
     * @var ShareService
     */
    private $shareService;

    /**
     * 获取商品列表
     * @RequestMapping(path="/v1/goods", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function index(RequestInterface $request)
    {
        $params = $request->all();
        $perPage = !empty($params['perpage']) ? $params['perpage'] : 100000;
        $field = ['*'];
        if (!empty($params['activityId']) && isset($params['type'])) {
            $list = $this->goodsService->activityGoods($params['activityId'], $params['type']);
        } else {
            $list = $this->goodsService->getGoodsList($params, (int)$perPage, $field);
        }
        if ($list['code']) {
            return $this->failed($list['code']);
        } else {
            return $this->success($list['data']->items(), '获取成功', $list['data']->total());
        }
    }

    /**
     * 获取商品信息
     * @RequestMapping(path="/v1/goods/{id:\d+}", methods="get")
     * @param int $id
     * @return array
     */
    public function info(int $id)
    {
        if (!$id) return $this->failed(ErrorCode::SYSTEM_INVALID);
        $field = [
            [
                'id', 'title', 'introduction', 'cate_id', 'crd_cate_id', 'scant_id', 'err', 'handle', 'goods_crm_code',
                'wx_crm_code', 'kz_type_id', 'kz_goods_id', 'read_pos_price', 'member_goods', 'read_pos_stock', 'is_home',
                'hot_id', 'sort', 'logo', 'share_image', 'image', 'content', 'status', 'ratio', 'unit_id', 'is_next_day',
                'is_today', 'lsy_goods_name', 'lsy_unit_name', 'lsy_class_name', 'safety_stock'
            ],
            [
                'goods_id', 'goods_spec', 'number_virtual', 'price_selling', 'member_func', 'discount', 'member_price',
                'number_stock', 'cost_price', 'price_market', 'commission', 'limite_num_per_day', 'goods_pick_time'
            ]
        ];
        $res = $this->goodsService->getInfoById((int)$id, $field);
        if (!$res['code']) {
            return $this->success($res['data'], '获取成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 添加商品
     * @PostMapping(path="/v1/goods", methods="post")
     * @param GoodsRequest $request
     *
     * @return array
     */
    public function store(GoodsRequest $request)
    {
        $params = $request->validated();
        $res = $this->goodsService->add($params);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code'], $res['msg'] ?? '');
        }
    }

    /**
     * 编辑商品
     * @PutMapping(path="/v1/goods/{id:\d+}", methods="put")
     * @param int $id
     * @param GoodsRequest $request
     *
     * @return array
     */
    public function update(int $id, GoodsRequest $request)
    {
        $params = $request->validated();
        $params['id'] = $id;
        $res = $this->goodsService->update($params);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 删除商品
     * @DeleteMapping(path="/v1/goods/{id:\d+}", methods="delete")
     * @param int $id
     *
     * @return array
     */
    public function delete(int $id)
    {
        $res = $this->goodsService->delete($id);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }


    /**
     * 查询当前商品下架店铺列表
     * @RequestMapping(path="/v1/goods/unbind/shop", methods="get")
     * @param RequestInterface $request
     *
     * @return array
     */
    public function goodsUnbindShop(RequestInterface $request)
    {
        $goodsId = $request->input('goods_id');
        $shopType = $request->input('shop_type') ?? 0;
        if (!$goodsId) return $this->failed(ErrorCode::SYSTEM_INVALID);
        $res = $this->resourceService->goodsUnbindShop((int)$goodsId, (int)$shopType);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 商品全局上下架
     * @RequestMapping(path="/v1/goods/{id:\d+}/status", methods="put")
     * @param int $id
     *
     * @return array
     */
    public function editstatus(int $id)
    {
        $res = $this->goodsService->editStatus('goods', $id);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 首页和热销控制
     * @PutMapping(path="/v1/goods/{id:\d+}/hot", methods="put")
     * @param int $id
     * @param RequestInterface $request
     * @return array
     */
    public function hot(int $id, RequestInterface $request)
    {
        $type = $request->input('type');
        $res = $this->goodsService->editHotOrHome($id, $type);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 获取首页热销商品
     * @RequestMapping(path="/v1/goods/hot", methods="get")
     * @param int $id
     * @return array
     */
    public function homeHot()
    {
        $res = $this->goodsService->homeHot();
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }

    /**
     * 获取小程序码
     * @RequestMapping(path="/v1/goods/{id:\d+}/minicode", methods="get")
     * @param int $id
     * @param RequestInterface $request
     * @return array
     * @throws \League\Flysystem\FileExistsException
     */
    public function miniAppCode(int $id, RequestInterface $request)
    {
        $scene = $request->input('scene');
        $page = $request->input('page');
        // 1：普通商品详情，2：秒杀商品详情
        $type = $request->input('type', 1);
        $res = $this->goodsService->getMiniAppCode($id, $type, $scene, $page);
        if (!$res['code']) {
            return $this->success($res['data'], '操作成功');
        } else {
            return $this->failed($res['code']);
        }
    }
    /**
     * 获取"小跑拼团"更多列表
     * @RequestMapping(path="/v1/api/goods/xp_group", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function getXPGroup(RequestInterface $request)
    {
        $pageRow = $this->checkPageRequest($request);
        if ($pageRow['code'] != 200) {
            return $pageRow;
        }
        $pageRow = $pageRow['data'];
        $res = $this->goodsService->getShopHomeGroup($pageRow['shop_id'], true, $pageRow['page'], 20);
        return $this->success($res, '获取成功');
    }
    /**
     * 检测 page 请求参数是否正确
     *
     * @param $request
     * @return array
     */
    public function checkPageRequest($request)
    {
        try {
            $shop_id = $request->input('shop_id');
            if (!$shop_id || !is_numeric($shop_id)) {
                $shop_id =20200606322061;
            }
            $page = intval($request->input('page', 1));
            if (!is_int($page)) {
                throw new \Exception('page 必须为整数');
            }
            $limit = intval($request->input('limit', 6));
            if (!is_int($limit)) {
                throw new \Exception('limit 必须为整数');
            }
            return $this->success(['shop_id' => $shop_id, 'page' => $page, 'limit' => $limit,], '获取成功');
        } catch (\Exception $e) {
            return $this->failed(ErrorCode::PARAMS_INVALID, $e->getMessage());
        }
    }

    /**
     * app获取次日达商品列表
     * @RequestMapping(path="/v1/app/goods", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function appGoodsList(RequestInterface $request)
    {
        $params = $request->all();
        $shop_id = (int)$params['shop_id'];
        $cate_id = (int)$params['cate_id'];
        if (empty($cate_id)) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $where = [
            'crd_cate_id' => $cate_id,
            'is_deleted' => 0,
            'status' => 1,
            'is_next_day' => '1'
        ];
        $res = $this->goodsService->appGoodsSortList($shop_id, $where);
        if ($res['code']) {
            return $this->failed($res['code']);
        } else {
            return $this->success($res['data']['goodsListPrice'], '获取成功', $res['data']['total']);
        }
    }

    /**
     * App商品搜索
     * @RequestMapping(path="/v1/app/goods/search", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function appSearchGoods(RequestInterface $request)
    {
        $params = $request->all();
//        $shopId =(int)$request->getAttribute('shop_id');
        $shopId = $params['shop_id'];
        if (empty($shopId)){
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $goodsName = trim($params['name']);
        $where = [
            'is_deleted'=>0,
            'status'=>1,
            'is_next_day' => '1'
        ];
        if(empty($goodsName)){
            return $this->success([]);
        }
        $goodsList =$this->goodsService->appNextDayGoods($where,$goodsName,$shopId);
        return $this->success($goodsList,'获取成功');
    }


    /**
     * 根据商品id更新状态
     * @RequestMapping(path="/v1/app/update", methods="post")
     * @param RequestInterface $request
     * @return array
     */
    public function updateByGoodsId( RequestInterface $request)
    {
        $params = $request->all();
        $goodsId = (int)$params['goods_id'] ;
        $shop_id = (int)$params['shop_id'];
        $isSelected = (int)$params['is_selected'] ?? 0;
        if (!$goodsId || !$shop_id) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $cartRes = $this->shareService::isSelected($goodsId,$shop_id,$isSelected);
        if (!$cartRes) {
            return $this->failed(ErrorCode::NOT_IN_FORCE);
        }
        return $this->success('', '成功');
    }

    /**
     * APP分享选中商品数量
     *
     * @RequestMapping(path="/v1/app/goods_number", methods="get")
     * @param RequestInterface $request
     * @return array
     */
    public function goodsNum(RequestInterface $request)
    {
        if (!$member_id = $request->input('shop_id')) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        $total = $this->shareService->getCartGoodsNumber(intval($member_id));
        return $this->success([], '', $total);
    }

    /**
     * 秒杀商品详情
     * @RequestMapping(path="/v1/api/seckill/{activity_goods_id:\d+}", methods="get")
     * @param int $activity_goods_id
     * @return array
     * @author liule
     */
    public function secKillGoodsDetail(int $activity_goods_id){
        $mid = $this->request->input('mid');
        if (!is_numeric($mid)) $mid = 0;
        $field = [
            'ac.begin_date',
            'ac.activity_prams',
            'g.introduction',
            'g.content',
            'g.logo',
            'g.image',
            'g.share_image',
            'gl.goods_pick_time',
            'gl.number_stock',
            'gl.limite_num_per_day',
            'ag.id as activity_goods_id',
            'ag.activityID as activity_id',
            'ag.goods_id',
            'ag.goods_title',
            'ag.group_id',
            'ag.goods_spec',
            'ag.price_selling',
            'ag.costprice',
            'ag.stock',
            'ag.spell_num',
            'ag.activityType as activity_type',
            'ag.per_can_buy_num',
            'IFNULL(cart.goods_num, 0) as cart_goods_num',
            'IF(sar.id, 1, 0) as remind_status'
        ];
        $res = $this->goodsService->secKillGoodsDetail($activity_goods_id, $field, (int)$mid);
        return $this->success($res, '获取成功');
    }

    /**
     * 及时达商品缓存操作
     * @RequestMapping(path="/v1/build/goods", methods="get")
     * op= build 构建缓存，op= del 删除
     * type= goods 构建公共商品资料，type=shop 构建每个店的商品资料
     * attr= timely 及时达商品资料，attr=tomorrow 次日达商品资料
     * @return array
     * @author liu
     * @date 2021-02-04 10:52
     */
    public function buildGoods(){
        $attr = $this->request->input('attr');
        $type = $this->request->input('type');
        $op = $this->request->input('op');
        if (empty($op) || empty($type) || empty($attr)) $this->failed(ErrorCode::PARAMS_INVALID);
        $ret = $this->goodsService->redisGoodsOp($op, $type, $attr);
        return $this->success($ret['data'], $ret['msg']);
    }

    /**
     * 龙收银库存缓存操作
     * @RequestMapping(path="/v1/lsy/stock", methods="get")
     * @author liu
     * @date 2021-01-28 17:23
     */
    public function getLsyStock(){
        $op = $this->request->input('op');
        if (empty($op)) $this->failed(ErrorCode::PARAMS_INVALID);
        $ret = $this->goodsService->redisLsyStockOp($op);
        return $this->success($ret['data'], $ret['msg']);
    }

}
